import { reactive, } from 'vue'
import { defineStore } from 'pinia'

const emptyState: AppState = {
  todos: [],
}

const LOCAL_STORAGE_KEY = 'my_vue3_todo_app'

const useLocalStore = defineStore('localStore', {
  actions: {
    fetch(): AppState {
      const storedStr = localStorage.getItem(LOCAL_STORAGE_KEY) || JSON.stringify(emptyState)
      return JSON.parse(storedStr) as AppState
    },

    save(appState: AppState) {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(appState))
    },
  }
})

const useTodoStore = defineStore('todo', () => {
  const localStore = useLocalStore()

  const state = reactive(localStore.fetch())

  function addTodo(newTodo: Todo) {
    state.todos.splice(0, 0, newTodo)
  }

  function removeTodo(todo: Todo) {
    // console.log('Remove todo: ', todo)
    state.todos.splice(state.todos.indexOf(todo), 1)
  }

  function saveLocalStorage(val: AppState) {
    localStore.save(val)
  }

  return { state, addTodo, removeTodo, saveLocalStorage, }
})

export { useTodoStore }
